import cv2
import pyzbar.pyzbar as pyzbar
import requests
import pyttsx3
import json

cap = cv2.VideoCapture(0)
continue_loop = True
while continue_loop:
    # 逐帧捕获
    ret, frame = cap.read()
    flag = cv2.waitKey(1)
    # 转为灰度图像
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    barcodes = pyzbar.decode(gray)
    for barcode in barcodes:
        # 提取二维码的位置,然后用边框标识出来在视频中
        (x, y, w, h) = barcode.rect
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # 字符串转换
        barcodeData = barcode.data.decode("utf-8")
        barcodeType = barcode.type
        # 在图像上面显示识别出来的内容
        text = "{}".format(barcodeData)
        cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
        # 打印识别后的内容
        print("[扫描结果]: {0}".format(barcodeData))    # 若不需要输出扫描结果就注释掉
        # 识别到结果后自动关闭
        for i in range(0, 1):
            flag = 27
        if flag == 27:  # 按下ESC键时
            url = "http://localhost:8080/camera/processQRCodeData"  # 这里需要后端服务器地址
            data = {"QR_content": text}
            # print(data)
            headers = {'Content-Type': 'application/json'}
            response = requests.post(url, json=data, headers=headers)
            # print(response.status_code)
            if response.status_code == 200:
                print("请求成功")
            else:
                print("请求失败")
            print(response.text)

            # 将 JSON 字符串解析为 Python 字典
            json_data = json.loads(response.text)

            # 获取 "message" 对应的值
            message_value = json_data['message']
            engine = pyttsx3.init()
            if message_value == "成功识别":
                engine.say("已成功！下一位！")
                #engine.runAndWait()
            elif message_value == "无效二维码":
                engine.say("无效！再来！")
                #engine.runAndWait()
            else:
                engine.say("已过期！请刷新！")
            engine.runAndWait()
            print("识别已暂停，按 'R' 键恢复或按其他任意键退出")
            while True:
                key_pressed = cv2.waitKey(100)  # 等待用户按键
                if key_pressed == ord('R') or key_pressed == ord('r'):  # 检查是否按下'R'键
                    print("识别恢复中...")
                    break  # 跳出等待子循环并重新开始主循环
                elif key_pressed != -1:  # 其他任意键被按下
                    continue_loop = False  # 设置标志位以结束主循环
                    break  # 跳出等待子循环
        else:
            break  # 其他情况下退出循环
    cv2.imshow("QRCODE", frame)
    #if flag == 27:#按下ESC键退出
     #   break
    #print("识别完成")

# 一切完成后，释放捕获
cap.release()
cv2.destroyAllWindows()


